
//生成器辅助

const Canvas = require('canvas');
const svgCaptcha = require('svg-captcha');
const uuid = require("node-uuid");
const moment = require('moment');
var validator = require('./validator');
var md5 = require('./md5');
const stringRandom = require('string-random');


var generator = {};

/**
 * 生成头像
 * @param {string} char 文字
 * @param {*} width     宽度
 * @param {*} height    高度
 * @param {*} bg_color  背景颜色
 */
generator.avatars = function (char, width, height, bg_color) {
    //设置头像昵称，如果为null或者为空时，设置为无
    var char = char == null ? "" : char == "" ? "" : char;
    if (!validator.isNull(char)) {
        //截取前四位,防止姓名复姓或者少数名族姓氏
        // char =char.substring(0,4);
        var type = 0;
        var index = 0;
        var max_index = 2;
        if (char.length > 2) {
            index = this.randomNum(1, max_index);
            char = this.randomFromStr(char, index);
        } else {
            char = this.randomFromStr(char, char.length);
        }
    }

    //设置头像大小
    if (validator.isNull(width)) {
        if (validator.isNull(height)) {
            height = 300;
            width = height;
        } else {
            width = height;
        }
    } else {
        if (validator.isNull(height)) {
            height = width;
        }
    }
    //设置头像内部文字大小
    var font_size = width > height ? (height / 2) : (width / 2);
    //设置头像内部字体
    var font_weight = 'normal';
    //设置头像背景颜色
    var colors = [
        "#31bc9f", "#33cc70", "#00CC99", "#99FFCC", "#00CC99", "#16a085", "#27ae60", "#2980b9", "#9999FF", "#00CCFF",
        "#CC0066", "#CC3300", "#CC3366", "#CC6666", "#CC3399", "#FF0066", "#FF0033", "#FF3300", "#FF3399", "#FF9999",
        "#00CCFF", "#00CCCC", "#4a94db", "#CC99FF", "#99FFCC", "#66CCFF", "#6699FF", "#33CCCC", "#33CC99", "#FFFF33",
        //"#31bc9f", "#33cc70", "#4a94db", "#9b5fb6", "#00CC99", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#00CCFF",
        //"#f1cb1e", "#e6761b", "#e7363b", "#00bcd4", "#00FFCC", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
    ];
    bg_color = bg_color == null ? colors[Math.floor((Math.random() * colors.length))] : bg_color == "" ? bg_color : colors[Math.floor((Math.random() * colors.length))];

    const canvas = Canvas.createCanvas(width, height);
    const context = canvas.getContext('2d');
    //头像背景颜色设置
    context.fillStyle = bg_color;
    context.fillRect(0, 0, canvas.width, canvas.height);

    //头像字体颜色设置
    context.fillStyle = '#FFFFFF';
    context.font = font_weight + ' ' + font_size + 'px sans-serif';
    context.textAlign = 'center';
    context.textBaseline = "middle";

    //context.fillText(char.charAt(0), font_size, font_size);
    context.fillText(char, font_size, font_size);
    var src = canvas.toDataURL("image/png");
    return src;
}

generator.randomFromStr = function (chars, len) {
    var d = '';
    if (validator.isNull(chars)) {
        return d;
    }
    var maxPos = chars.length;
    if (len > maxPos) {
        len = maxPos;
    }
    for (i = 0; i < len; i++) {
        d += chars.charAt(Math.floor(Math.random() * maxPos));
    }
}

/**
 * 随机生成指定范围内的数
 * @param {number} minNum 最小值
 * @param {number} maxNum 最大值
 */
generator.randomNum = function (minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            //或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
            break;
        default:
            return 0;
            break;
    }
}

/**
 * 从指定数组中随机抽取一个
 * @param {Array} arr 数组
 */
generator.randomFromArr = function (arr) {
    if (validator.isNull(arr)) {
        return null;
    }
    return arr[Math.floor(Math.random() * arr.length)];
}

/**
 * 生成唯一id。uuid随机字符 + 时间戳 + 随机128位英文数字组合 进行md5，降低重复性
 */
generator.uid = function () {
    var uid = uuid.v4();
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'd', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    //var chars = ['0','1','2','3','4','5','6','7','8','9','a','d','c','d','e'];
    var cstr = "";
    //var arr =[4,5,6,7,8];
    var len = 128;
    var now = Date.now();
    //len =this.randomFromArr(arr);
    for (var i = 0; i < len; i++) {
        var id = Math.floor(Math.random() * chars.length);
        cstr += chars[id];
    }
    uid = uid.replace(/-/g, '').trim();
    uid += now;
    uid += cstr;
    uid = md5.md5(uid);
    return uid;
}

// generator.uid = function(hasChar=false) {
//     var uid =uuid.v4();
//     if(hasChar===false){
//         uid =uid.replace(/-/g, '').trim();
//     }
//     return uid;
// }

generator.getKey = function (len = 16,full =false) {
    //var char = '0123456789abcde';
    // var char = ['0','1','2','3','4','5','6','7','8','9','a','d','c','d','e'];
    var d ='';
    if(full){
        d = stringRandom(len,true);
    }else{
        d = stringRandom(len);
    }
    return d;
}

generator.getFullKey = function (len = 16) {
    var char = '0123456789!@#$%^&*?+=/.<>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var d = stringRandom(len,{letters:char});
    return d;
}

/**
 * 随机生成一个姓名，姓+名字
 */
generator.randomRealName = function () {
    var familyNames = new Array(
        "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "黄", "孟", "尹", "余", "林",
        "蒋", "沈", "韩", "杨", "秦", "许", "何", "吕", "张", "孔", "曹", "袁", "华", "魏", "唐",
        "陶", "谢", "苏", "潘", "葛", "奚", "范", "彭", "鲁", "韦", "马", "方", "俞", "任", "柳",
        // "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", 
        // "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
        // "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", 
        // "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章",
        // "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦", 
        // "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳",
        // "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", 
        // "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常",
        // "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", 
        // "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹"
    );
    var givenNames = new Array(
        '月', '永', '悦', '正', '勇', '晨', '琪', '华',
        '昊', '雨', '佳', '伟', '亮', '涛', '涵', '若',
        '甜', '敏', '尚', '浩', '豪', '辉', '鸿', '阳',
        '文', '晓', '瑾', '辉', '鸿', '阳', '鑫', '茜',
        '子璇', '易轩', '浩晨', '晨涛', '文昊', '欣欣',
        '亦菲', '熙涵', '文杰', '欣源', '宜豪', '伟洋',
        '佳琪', '子辰', '涵璐', '雨泽', '萌萌', '若萌',
        '雅涵', '清妍', '佳钰', '晓庆', '嘉乐', '晨涵',
        '一鸣', '语晨', '晶滢', '明远', '泽远', '建林',
    );
    var first = this.randomFromArr(familyNames);
    var given = this.randomFromArr(givenNames);
    var name = familyName + givenName;
    return name;
}

/**
 * 随机生成一个合法手机号
 */
generator.randomMobile =function(){
    var prefixArray = new Array("130", "131", "132", "133", "135", "137", "138", "157","159","170","186", "187", "189");
    var pre =this.randomFromArr(prefixArray);
    for (var j = 0; j < 8; j++) {
        pre += this.randomNum(0,9);
    }
    return pre;
}

/**
 * 随机生成一张合法银行卡号
 */
generator.randomBankCard =function(){
    var prefix =['622202','622848','622700','622262','621661','622666','622622','622556','622588','622155','622689','622630','622908','621717','622323','622309'];
    var pre =this.randomFromArr(prefix);
    for (var j = 0; j < 13; j++) {
        pre += this.randomNum(0,9);
    }
    return pre;
}

/**
 * 随机生成合法身份证号
 */
generator.randomIDCard =function(){
    var address = this.randomNum(999999, 100000);
    var date = new Date();
    var yearfull = date.getFullYear();
    var y = this.randomNum(yearfull + 1, yearfull - 70);
    var m = this.randomNum(13, 1);
    var d = this.randomNum(30, 1);
    var z = this.randomNum(9999, 1000);
    if (m < 10) {
        m = '0' + m;
    }
    if (d < 10) {
        d = '0' + d;
    }
    return address + '' + y + '' + m + '' + d + '' + z + '';
}

/************** 生成svg字符验证码 https://gitee.com/steambap/svg-captcha */
//1、svgCaptcha.create(options) 生成常规字符验证码
// 如果没有任何参数，则生成的 svg 图片有4个字符。
// size: 4 // 验证码长度
// ignoreChars: '0o1i' // 验证码字符中排除 0o1i
// noise: 1 // 干扰线条的数量
// color: true // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
// background: '#cc9966' // 验证码图片背景颜色
// 该函数返回的对象拥有以下属性
// data: string // svg 路径
// text: string // 验证码文字

//2、svgCaptcha.createMathExpr(options) 生成数学计算验证码，比如 1+2=?

//3、svgCaptcha.loadFont(url) 加载自定义字体

//4、svgCaptcha.options 配置
//size, noise, color, background，width，height，fontSize，charPreset

//5、svgCaptcha.randomText([size|options]) 返回随机字符串

//6、svgCaptcha(text, options) 基于字符生成svg

generator.svgCaptcha = svgCaptcha;



module.exports = generator;